<template>
  <div class="mail-config">
    <Form
      :model="formState"
      style="width: 1010px"
      :label-col="{ style: { width: '210px' } }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
      label-align="right"
      :colon="false"
    >
      <FormItem
        name="JE_SYS_EMAIL_SENDTITLE"
        class="JE_SYS_EMAIL_SENDTITLE"
        v-bind="validateInfos.JE_SYS_EMAIL_SENDTITLE"
        :label="$t('mail.sendersName')"
      >
        <Input v-model:value="formState.JE_SYS_EMAIL_SENDTITLE" class="myInput" />
        <div class="text">
          <i>{{ $t('mail.sendersNameTip') }}</i>
        </div>
      </FormItem>
      <FormItem
        name="JE_SYS_EMAIL_SERVERHOST"
        class="JE_SYS_EMAIL_SERVERHOST"
        :label="$t('mail.smtp')"
      >
        <Input v-model:value="formState.JE_SYS_EMAIL_SERVERHOST" class="myInput" />
        <div class="text">
          <i>{{ $t('mail.smtpTip') }}</i>
        </div>
      </FormItem>
      <FormItem name="JE_SYS_EMAIL_SSL" class="JE_SYS_EMAIL_SSL interval" :label="$t('mail.SSL')">
        <Select
          v-model="formState.JE_SYS_EMAIL_SSL"
          :allow-clear="false"
          :default-value="formState.JE_SYS_EMAIL_SSL"
          :options="SLLList"
          class="myInput"
          @change="($event) => handleChange('JE_SYS_EMAIL_SSL', $event)"
        >
        </Select>
        <div class="text">
          <i>{{ $t('mail.SSLTip') }}</i>
        </div>
      </FormItem>
      <FormItem
        name="JE_SYS_EMAIL_SERVERPORT"
        class="JE_SYS_EMAIL_SERVERPORT"
        :label="$t('mail.post')"
      >
        <Input v-model:value="formState.JE_SYS_EMAIL_SERVERPORT" class="myInput" />
        <div class="text">
          <i>{{ $t('mail.postTip') }}</i>
        </div>
      </FormItem>
      <FormItem name="JE_SYS_EMAIL_AUTHCODE" class="JE_SYS_EMAIL_AUTHCODE" :label="$t('mail.code')">
        <Input v-model:value="formState.JE_SYS_EMAIL_AUTHCODE" class="myInput" />
        <div class="text">
          <i>{{ $t('mail.codeTip') }}</i>
        </div>
      </FormItem>
      <FormItem
        name="class"
        class="JE_SYS_EMAIL_USERNAME"
        v-bind="validateInfos.JE_SYS_EMAIL_USERNAME"
        :label="$t('mail.email')"
      >
        <Input v-model:value="formState.JE_SYS_EMAIL_USERNAME" class="myInput" />
        <div class="text">
          <i>{{ $t('mail.emailTip') }}</i>
        </div>
      </FormItem>
      <FormItem
        name="JE_SYS_EMAIL_PASSWORD"
        class="JE_SYS_EMAIL_PASSWORD"
        :label="$t('mail.password')"
      >
        <Input v-model:value="formState.JE_SYS_EMAIL_PASSWORD" class="myInput" />
        <div class="text">
          <i>{{ $t('mail.passwordTip') }}</i>
        </div>
      </FormItem>
      <FormItem
        name="JE_SYS_EMAIL_SERVERVALIDATE"
        class="JE_SYS_EMAIL_SERVERVALIDATE"
        :label="$t('mail.verification')"
      >
        <Select
          v-model="formState.JE_SYS_EMAIL_SERVERVALIDATE"
          :allow-clear="false"
          :default-value="formState.JE_SYS_EMAIL_SERVERVALIDATE"
          :options="SLLList"
          class="myInput"
          @change="($event) => handleChange('JE_SYS_EMAIL_SERVERVALIDATE', $event)"
        />
        <div class="text">
          <i>{{ $t('mail.verificationTip') }}</i>
        </div>
      </FormItem>
      <FormItem name="btn" label="&nbsp;"
        ><Button type="primary" @click="clickEvent">{{ $t('mail.verify') }}</Button></FormItem
      >
    </Form>
    <div v-if="visable">
      <MailSecondary v-model:visible="visable" />
    </div>
  </div>
</template>

<script>
  import { defineComponent, onMounted, onUnmounted, reactive, ref } from 'vue';
  import { Input, Form, Button, Select, Modal } from '@jecloud/ui';
  import VueEvent from '@/helper/model/event';
  import { useOpenDialog } from '@/hooks';
  import { saveConfigData } from '@/api';
  import { onScroll, scrollToTop } from '@/utils/utils';
  import MailSecondary from './mail-secondary.vue';
  import { useI18n } from '@common/locales';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'MailConfig',
    components: {
      Form,
      FormItem: Form.Item,
      Input,
      Select,
      Button,
      // eslint-disable-next-line
      Modal,
      MailSecondary,
    },
    props: {
      dataAll: {
        type: Array,
        default: () => [],
      },
    },
    setup(props) {
      const I18n = useI18n().messages.zh_CN;
      // 验证框的显隐
      const visable = ref(false);

      const formState = reactive({
        JE_SYS_EMAIL_SENDTITLE: '',
        JE_SYS_EMAIL_SERVERHOST: 'smtp.263.net',
        JE_SYS_EMAIL_SSL: true,
        JE_SYS_EMAIL_SERVERPORT: '465',
        JE_SYS_EMAIL_AUTHCODE: '',
        JE_SYS_EMAIL_USERNAME: 'suanbanyun@china-hbp.com',
        JE_SYS_EMAIL_PASSWORD: 'JEvirus81231',
        JE_SYS_EMAIL_SERVERVALIDATE: true,
      });
      let meta = {};
      let res = {};
      // 装换数据成formState类型
      const changeDataType = (parame) => {
        res = parame.filter((item) => {
          return item.code === 'mail-config';
        });
        res[0]?.items.find((item) => {
          formState[item.code] = item['value'];
        });
        meta = JSON.parse(JSON.stringify(formState));
      };
      changeDataType(props.dataAll);
      // 数据是否改变
      meta = JSON.parse(JSON.stringify(formState));
      const isChange = () => {
        return Object.keys(meta).every((item) => {
          return meta[item] === formState[item];
        });
      };
      // 切换导航栏
      const changeBar = () => {
        VueEvent.emit('saveResult', isChange());
      };
      // 提交验证
      const onSubmit = () => {
        validate()
          .then(() => {
            if (!isChange()) {
              saveConfigData({
                attribute: 'mail-config',
                allFields: JSON.stringify(formState),
                type: '',
              }).then(
                (meta = JSON.parse(JSON.stringify(formState))),
                Modal.notice('保存成功', 'success'),
                VueEvent.emit('saveResult', isChange()),
                VueEvent.emit('changeAllData', { item: 'mail-config', formState }),
              );
            } else {
              // 如果显示了子页面就不提示
              Modal.notice('无数据操作!', 'info');
            }
          })
          .catch(() => {
            // console.log('error', err);
          });
      };

      // 保存回调
      const isSaveCallback = () => {
        if (isChange()) return changeBar();
        useOpenDialog({
          attribute: 'mail-config',
          allFields: JSON.stringify(formState),
        });
      };

      // sll选项
      const SLLList = [
        { value: 'true', label: I18n.yes },
        { value: 'false', label: I18n.no },
      ];
      const handleChange = (code, e) => {
        formState[code] = e;
      };

      // 校验规则
      const rulesRef = reactive({
        JE_SYS_EMAIL_SENDTITLE: [{ required: true, message: '该输入项为必填项' }],
        JE_SYS_EMAIL_USERNAME: [
          { required: true, message: '该输入项为必填项' },
          {
            pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
            message: '请输入正确邮箱地址',
          },
        ],
      });
      const { resetFields, validate, validateInfos } = useForm(formState, rulesRef, {
        // onValidate: (...args) => console.log(...args),
      });

      // 保存的回调事件
      const clickCallback = () => {
        onSubmit();
      };
      const clickEvent = () => {
        visable.value = true;
      };
      // 回滚到顶部
      onMounted(() => {
        scrollToTop();
      });
      VueEvent.on('toolbarSaveEventS', clickCallback);
      VueEvent.on('securityConfigCheck', clickCallback);
      VueEvent.on('isSave', isSaveCallback);
      VueEvent.on('fadeScroll', onScroll);
      onUnmounted(() => {
        VueEvent.off('toolbarSaveEventS', clickCallback);
        VueEvent.off('isSave', isSaveCallback);
        VueEvent.off('fadeScroll', onScroll);
        VueEvent.off('securityConfigCheck', clickCallback);
      });
      return {
        formState,
        SLLList,
        handleChange,
        visable,
        clickEvent,
        validateInfos,
        resetFields,
        // onSubmit,
      };
    },
  });
</script>

<style lang="less" scoped>
  .mail-config {
    height: 700px;
    padding: 30px 0 30px 0px;
  }
</style>
